package com.juku2024.juku.viewmodel

import com.juku2024.juku.base.BaseApplication
import com.juku2024.juku.db.NoteRoomUtils
import com.juku2024.juku.db.entity.AlbumModel
import com.juku2024.juku.network.api.Api
import com.juku2024.juku.network.retrofit.OnRetrofitResultListener
import com.juku2024.juku.network.retrofit.RetrofitUtils
import com.juku2024.juku.request.ViewAllRequest
import com.juku2024.juku.tools.MD5Utils
import kotlinx.coroutines.*

class AlbumViewModel : BaseViewModel() {

    fun getAlbumList(
        id: Long,
        version: Int,
        success: (t: AlbumModel) -> Unit,
        fail: (msg: String?) -> Unit
    ) {
        // 查当前数据表是否有数据
        val dao = NoteRoomUtils.getInstance().albumDao()
        doBaseHttp({
            if (BaseApplication.isLimited) {
                return@doBaseHttp null
            }
            val model = withContext(Dispatchers.IO) { dao.query(id) }
            return@doBaseHttp if (model?.version == version) {
                success(model)
                model
            } else {
                null
            }
        },{
            dao.delete(id)
            val appId = getAppId()
            val timestamp = getSecondTimestamp()
            val sign = MD5Utils.getMD5String(id, version, appId, getAppKey(), timestamp, getExtra())
            val request = ViewAllRequest(id, version, appId, timestamp, sign)
            return@doBaseHttp RetrofitUtils.instance.getApi(Api::class.java).getAlbumList(id, getCommonRequest(request))
        }, object : OnRetrofitResultListener<AlbumModel> {
            override fun onSuccess(t: AlbumModel) {
                t.id = id
                dao.insert(t)
                if (isNotActive()) return
                success(t)
            }

            override fun onFailed(msg: String) {
                if (isNotActive()) return
                fail(msg)
            }

        })
    }



}